package lookie.swing.tree.model.util;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import javax.swing.tree.TreeNode;

import org.jdesktop.swingworker.SwingWorker;

import lookie.swing.tree.model.DeferredTreeNode;
import lookie.swing.tree.model.PlaceholderNode;
import lookie.swing.tree.model.TreeNodeProvider;

public class DeferredTreeNodeLoader {

	private TreeNodeProvider provider;

	public DeferredTreeNodeLoader(TreeNodeProvider provider) {
		super();
		this.provider = provider;
	}

	public void load(final DeferredTreeNode parent) {
		SwingWorker<TreeNode[], Object> sw = new SwingWorker<TreeNode[], Object>() {

			private TreeNode[] nodes = null;

			@Override
			protected TreeNode[] doInBackground() throws Exception {
				nodes = provider.getChildren(parent);
				return nodes;
			}

			@Override
			protected void done() {
				if (parent.isDeferred()) {
					parent.fill(nodes);
					postDeferred(parent);
				}
			}

		};
		sw.execute();
		try {
			TreeNode[] nodes = sw.get(100, TimeUnit.MILLISECONDS);
			parent.fill(nodes);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TimeoutException e) {
			parent.fillWithPlaceholder(new PlaceholderNode(parent));
		}
	}

	public void postDeferred(DeferredTreeNode parent) {
		
	}

}
